const http = require('http')

const data = require('./data')
const server = http.createServer((req, res) => {

    if (req.url === '/') {
        //新闻列表
        res.setHeader('content-type', 'text/html;charset=utf-8')

        let str = `<ul>`
        for (let i = 0; i < data.length; i++) {
            str += `
    <li><a href="/detail?id=${data[i].id}">${data[i].newsTitle}</a></li>`
        }
        str += `</ul>`
        res.end(str)

    }
    if (req.url.split('?')[0] === '/detail') {

        //新闻详情页
        //1.获取id
        res.setHeader('content-type', 'text/html;charset=utf-8')
        let id = req.url.split('=')[1]

        //2.通过id查找对应对象
        let obj = data.find((item) => {
            // console.log(item);
            return item.id === id
        })

        // console.log(obj);
        let str2 = `<h3>${obj.newsTitle}</h3>
       <p>${obj.newsContent}</p>`
        res.end(str2)

    }
})

server.listen(80, () => {
    console.log('启动成功');
})